import * as API from '../../api/homeApi';
import * as loginAPI from '../../api/loginApi';
import * as util from '../../utils/util';
import * as myAPI from '../../api/myApi';
let app = getApp ();
Page ({
  /**
   * 页面的初始数据
   */
  data: {
    //===========首页=========
    companyName: '',
    attentPeopleNum: 0,
    customNum: 0,
    orderNum: 0,
    unReadNum: 0,
    //===========我的页面=========
    phone: '',
    photo: '',
    isEnterpriseUser: false,
    realName: '',
    currentCompanyName: '',
    roleNames: '',
    email: '',
    //========公共==========
    presentPage: 'home',
    extra_data: {
      token: '',
      key: '',
    },
  },
  
  //================================公共方法区开始==========================================
  //加载用户信息
  getUserInfo: function () {
    API.updateSwitchInfo ().then (res => {
      app.globalData.user.companyName = res.companyName;
      app.globalData.user.companyId = res.companyId;
      this.setData ({
        companyName: res.companyName || '',
        comapnyId: res.companyId || '',
        phone: (res.Employee && res.Employee.phone) || '',
        photo: res.photo || '',
        roleNames: res.roleNames || '',
        realName: res.realName || '',
        currentCompanyName: res.companyName || '',
        email: (res.Employee && res.Employee.email) || '',
      });
    });
  },
  //更新导航栏标题颜色
  updateNavication: function () {
    if (this.data.presentPage == 'userInfo') {
      wx.setNavigationBarTitle ({
        title: '我的',
      });
      wx.setNavigationBarColor ({
        frontColor: '#000000',
        backgroundColor: '#fafdff',
      });
    } else {
      wx.setNavigationBarTitle ({
        title: '普为',
      });
      wx.setNavigationBarColor ({
        frontColor: '#ffffff',
        backgroundColor: '#1c82d4',
      });
    }
  },
  // 登录随机账号
  randomAccount: function () {
    let postbody = {
      loginType: 'APPLETS_PROVIDER',
    };
    loginAPI.RandomAccount (postbody).then (
      res => {
        let phoneArr = res.phoneList;
        let phone = phoneArr[Math.floor (Math.random () * phoneArr.length)];
        let postbody = {
          phone: phone,
        };
        loginAPI.re_login (postbody).then (
          res => {
            if (res) {
              app.globalData.user = res.user;
              wx.setStorageSync ('curShardingId', res.user.companyId);
              wx.setStorageSync ('token', res.user.token);
              this.updateNavication ();
              this.loadData ();
            } else {
              util.toast ('获取数据失败,请稍后再试');
            }
          },
          err => {
            util.toast (err || '数据错误,请稍后再试');
          }
        );
      },
      err => {
        util.toast (err || '数据错误,请稍后再试');
      }
    );
  },
  //================================公共方法区结束==========================================

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    // this.setData ({
    //   presentPage: options.presentPage || 'home',
    // });
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    // wx.request({
    //   // 获取token
    //   url: 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential',
    //   data: {
    //     appid: 'wxe52be9daba3f2861', // 小程序appid
    //     secret: 'f4aba2a6024dad21ef45604ac5e414e5' // 小程序秘钥
    //   },
    //   success(res) {
    //     // res.data.access_token 
    //     wx.request({
    //       url: 'https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=' + res.data.access_token,
    //       method: 'POST',
    //       data: {
    //         'path': "/pages/index/index",
    //         "width": 430,
    //         "scene":"a=1"
    //       },
    //       success(res) {
    //         console.log(res.data)
    //         // 后台转二进制流，后台获取后，直接保存为图片，然后将图片路径返回给前台
    //         // 前端转，如上 
    //       }
    //     })
    //   }
    // })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {},

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {},

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    wx.showLoading ({
      title: '正在刷新',
    });
    this.loadData ();
    wx.stopPullDownRefresh ();
    wx.hideLoading ();
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {},

  loadData: function () {
    // =====================================我的用戶信息頁面數據加載===================
    if (this.data.presentPage == 'userInfo') {
      this.setKey ();
      this.getUserInfo ();
    } else {
      // ====================================首頁數據加載===========================
      this.setKey ();
      this.getHomeData ();
      this.getUnreadMsg ();
      this.getUserInfo ();
    }
  },

  //==========================================首页js开始==========================================================
  //==========================================首页js开始==========================================================
  //==========================================首页js开始==========================================================

  //展示首页
  showHomePage: function (e) {
    let presentPage = this.data.presentPage;
    this.setData ({
      presentPage: 'home',
    });
    if (presentPage != 'home') {
      this.updateNavication ();
      this.loadData ();
    }
  },

  homePageGoto: function (options) {
    var url = options.currentTarget.dataset.url;
    util.preventMoreClick (this, () => {
      wx.navigateTo ({
        url: url,
      });
    });
  },

  // 获取共享数据
  getHomeData: function () {
    API.getHomeData ().then (
      data => {
        this.setData ({
          attentPeopleNum: data.attentPeopleNum || 0,
          customNum: data.customNum || 0,
          orderNum: data.orderNum || 0,
        });
      },
      err => {}
    );
  },

  getUnreadMsg: function () {
    API.getUnReadMsg ().then (res => {
      this.setData ({
        unReadNum: res,
      });
    });
  },

  gotoCompany: function (e) {
    util.preventMoreClick (this, () => {
      let companyId = e.currentTarget.dataset.companyId;
      wx.navigateTo ({
        url: './enterprises/enterprises?companyId=' + companyId,
      });
    });
  },

  closePlace: function (e) {
    let bottomShow = e.currentTarget.dataset.bottomShow;
  },

  //==========================================我的页面js开始==========================================
  //==========================================我的页面js开始=========================================
  //==========================================我的页面js开始=========================================
  //显示我的页面
  showMyPage: function () {
    let presentPage = this.data.presentPage;
    this.setData ({
      presentPage: 'userInfo',
    });
    if (presentPage != 'userInfo') {
      this.updateNavication ();
      this.getUserInfo ();
    }
  },

  gotoAccount: function () {
    wx.navigateTo ({
      url: '/pages/me/account/account',
    });
  },

  setKey: function () {
    this.setData ({
      'extra_data.key': new Date ().getTime (),
      'extra_data.token': wx.getStorageSync ('token'),
    });
    wx.setStorageSync ('extra_data', this.data.extra_data);
  },

  gotoSuggestion: function () {
    util.preventMoreClick (this, () => {
      wx.navigateTo ({
        url: '/pages/me/feedback/feedback?phone=' + this.data.phone,
      });
    });
  },

  gotoAbout: function () {
    util.preventMoreClick (this, () => {
      wx.navigateTo ({
        url: '/pages/me/about/about?phone=' + this.data.phone,
      });
    });
  },

  gotoSetting: function () {
    util.preventMoreClick (this, () => {
      wx.navigateTo ({
        url: '/pages/me/account/accountSetting',
      });
    });
  },
});
